package com.gancp.controller;

import com.gancp.domain.User;
import com.gancp.service.RedisManager;
import com.gancp.service.UserBiz;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by GCP on 2018/4/27.
 * 登录处理
 */
@Controller
@RequestMapping("login")
public class LoginController {

    private static Logger log = LoggerFactory.getLogger( LoginController.class );

    @Autowired
    private UserBiz userBiz;

    @Autowired
    private RedisManager redisManager;

    /**
     * @Author gancp
     * @Date 时间被黑洞吸走了
     * @Descripition 进入登录页面
     **/
    @RequestMapping("")
    public String login() {

        return "login";
    }

    @RequestMapping("/check")
    public @ResponseBody
    String loginCheck(HttpServletRequest request) {
        String username = request.getParameter( "username" );
        String password = request.getParameter( "password" );
       /* if (StringUtils.isEmpty( username ) || StringUtils.isEmpty( password )) {
            return "login_fail";
        } else {
            try {
                boolean flag = userBiz.checkUserByName( username, password );
                if (!flag) {
                    return "login_fail";
                }
            } catch (Exception e) {
                return "login_fail";
            }
            HttpSession session = request.getSession();
            User user = userBiz.findUserByUserName( username );
            session.setAttribute( Constans.USER_INFO, user );
            log.info( "用户" + user.getUsername() + "登录成功！" );
            redisManager.set( "userinfo", user.getRealName() );
            return "login_success";
        }*/
        UsernamePasswordToken token = new UsernamePasswordToken( username, password );
        token.setRememberMe( true );
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login( token );
            SecurityUtils.getSubject().getSession().setTimeout( 1000 * 180 );

        } catch (Exception e) {
            return "login_fail";
        }
        return "login_success";
    }

    @RequestMapping("/register")
    public @ResponseBody
    String register(@RequestBody User user) {
        try {
            userBiz.insertUser( user );
        } catch (Exception e) {
            log.info( user.getUsername() + "创建用户失败！" + e.getMessage() );
        }
        log.info( user.getUsername() + "创建用户成功！" );
        return "success";
    }


}
